Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | /**
* Contact Controller
* Manages contacts and contact groups for tenants
*
* @module controllers/ContactController
*/
const { pool } = require('../config/database');
const { logger } = require('../config/logger');
const { asyncHandler } = require('../middleware/errorHandler');
class ContactController {
/**
* Get all contacts for tenant
* GET /api/tenant/contacts
*/
static getContacts = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { group_id, search, limit = 50, offset = 0 } = req.query;
logger.info('Getting contacts', { tenantId, filters: { group_id, search, limit, offset } });
try {
let query = `
SELECT
c.id,
c.name,
c.phone,
c.email,
c.group_id,
c.tags,
c.notes,
c.created_at,
c.updated_at,
cg.group_name
FROM contacts c
LEFT JOIN contact_groups cg ON c.group_id = cg.id AND cg.tenant_id = c.tenant_id
WHERE c.tenant_id = ?
`;
const params = [tenantId];
if (group_id) {
query += ` AND c.group_id = ?`;
params.push(group_id);
}
if (search) {
query += ` AND (c.name LIKE ? OR c.phone LIKE ? OR c.email LIKE ?)`;
const searchTerm = `%${search}%`;
params.push(searchTerm, searchTerm, searchTerm);
}
query += ` ORDER BY c.name ASC LIMIT ? OFFSET ?`;
params.push(parseInt(limit), parseInt(offset));
const [contacts] = await pool.query(query, params);
// Get total count
let countQuery = `SELECT COUNT(*) as total FROM contacts WHERE tenant_id = ?`;
const countParams = [tenantId];
if (group_id) {
countQuery += ` AND group_id = ?`;
countParams.push(group_id);
}
if (search) {
countQuery += ` AND (name LIKE ? OR phone LIKE ? OR email LIKE ?)`;
const searchTerm = `%${search}%`;
countParams.push(searchTerm, searchTerm, searchTerm);
}
const [countResult] = await pool.query(countQuery, countParams);
logger.info('Contacts retrieved', { tenantId, count: contacts.length });
return res.json({
success: true,
data: contacts,
total: countResult[0].total
});
} catch (error) {
logger.error('Error getting contacts', {
tenantId,
error: error.message,
stack: error.stack
});
return res.status(500).json({
success: false,
error: 'Failed to load contacts'
});
}
});
/**
* Get single contact
* GET /api/tenant/contacts/:id
*/
static getContact = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { id } = req.params;
try {
const [contacts] = await pool.query(
`SELECT c.*, cg.group_name
FROM contacts c
LEFT JOIN contact_groups cg ON c.group_id = cg.id
WHERE c.id = ? AND c.tenant_id = ?`,
[id, tenantId]
);
if (contacts.length === 0) {
return res.status(404).json({
success: false,
error: 'Contact not found'
});
}
return res.json({
success: true,
data: contacts[0]
});
} catch (error) {
logger.error('Error getting contact', { tenantId, contactId: id, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to load contact'
});
}
});
/**
* Create contact
* POST /api/tenant/contacts
*/
static createContact = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { name, phone, email, group_id, tags, notes } = req.body;
if (!name || !phone) {
return res.status(400).json({
success: false,
error: 'Name and phone are required'
});
}
try {
// Check contact limit for tenant's plan
const [planLimit] = await pool.query(
`SELECT sp.max_contacts
FROM tenants t
JOIN subscription_plans sp ON t.plan_id = sp.id
WHERE t.id = ?`,
[tenantId]
);
if (planLimit.length > 0 && planLimit[0].max_contacts > 0) {
const [contactCount] = await pool.query(
'SELECT COUNT(*) as count FROM contacts WHERE tenant_id = ?',
[tenantId]
);
if (contactCount[0].count >= planLimit[0].max_contacts) {
return res.status(403).json({
success: false,
error: 'Contact limit reached for your plan'
});
}
}
const [result] = await pool.query(
`INSERT INTO contacts (tenant_id, name, phone, email, group_id, tags, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[tenantId, name, phone, email || null, group_id || null, tags || null, notes || null]
);
logger.info('Contact created', { tenantId, contactId: result.insertId });
return res.json({
success: true,
message: 'Contact created successfully',
data: { id: result.insertId }
});
} catch (error) {
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
success: false,
error: 'Phone number already exists'
});
}
logger.error('Error creating contact', { tenantId, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to create contact'
});
}
});
/**
* Update contact
* PUT /api/tenant/contacts/:id
*/
static updateContact = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { id } = req.params;
const { name, phone, email, group_id, tags, notes } = req.body;
try {
const [result] = await pool.query(
`UPDATE contacts
SET name = ?, phone = ?, email = ?, group_id = ?, tags = ?, notes = ?
WHERE id = ? AND tenant_id = ?`,
[name, phone, email || null, group_id || null, tags || null, notes || null, id, tenantId]
);
if (result.affectedRows === 0) {
return res.status(404).json({
success: false,
error: 'Contact not found'
});
}
logger.info('Contact updated', { tenantId, contactId: id });
return res.json({
success: true,
message: 'Contact updated successfully'
});
} catch (error) {
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
success: false,
error: 'Phone number already exists'
});
}
logger.error('Error updating contact', { tenantId, contactId: id, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to update contact'
});
}
});
/**
* Delete contact
* DELETE /api/tenant/contacts/:id
*/
static deleteContact = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { id } = req.params;
try {
const [result] = await pool.query(
'DELETE FROM contacts WHERE id = ? AND tenant_id = ?',
[id, tenantId]
);
if (result.affectedRows === 0) {
return res.status(404).json({
success: false,
error: 'Contact not found'
});
}
logger.info('Contact deleted', { tenantId, contactId: id });
return res.json({
success: true,
message: 'Contact deleted successfully'
});
} catch (error) {
logger.error('Error deleting contact', { tenantId, contactId: id, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to delete contact'
});
}
});
/**
* Import contacts from CSV
* POST /api/tenant/contacts/import
*/
static importContacts = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { contacts } = req.body; // Array of {name, phone, email, group_id}
if (!Array.isArray(contacts) || contacts.length === 0) {
return res.status(400).json({
success: false,
error: 'Contacts array is required'
});
}
try {
// Check contact limit
const [planLimit] = await pool.query(
`SELECT sp.max_contacts
FROM tenants t
JOIN subscription_plans sp ON t.plan_id = sp.id
WHERE t.id = ?`,
[tenantId]
);
const [contactCount] = await pool.query(
'SELECT COUNT(*) as count FROM contacts WHERE tenant_id = ?',
[tenantId]
);
const currentCount = contactCount[0].count;
const maxContacts = planLimit[0]?.max_contacts || 0;
if (maxContacts > 0 && (currentCount + contacts.length) > maxContacts) {
return res.status(403).json({
success: false,
error: `Cannot import ${contacts.length} contacts. Limit: ${maxContacts}, Current: ${currentCount}`
});
}
let imported = 0;
let failed = 0;
const errors = [];
for (const contact of contacts) {
try {
await pool.query(
`INSERT INTO contacts (tenant_id, name, phone, email, group_id)
VALUES (?, ?, ?, ?, ?)`,
[tenantId, contact.name, contact.phone, contact.email || null, contact.group_id || null]
);
imported++;
} catch (error) {
failed++;
errors.push({ contact: contact.name, error: error.code === 'ER_DUP_ENTRY' ? 'Duplicate phone' : error.message });
}
}
logger.info('Contacts imported', { tenantId, imported, failed });
return res.json({
success: true,
message: `Imported ${imported} contacts, ${failed} failed`,
data: { imported, failed, errors: errors.slice(0, 10) }
});
} catch (error) {
logger.error('Error importing contacts', { tenantId, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to import contacts'
});
}
});
/**
* Get all contact groups
* GET /api/tenant/contact-groups
*/
static getGroups = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
logger.info('Getting contact groups', { tenantId });
try {
const [groups] = await pool.query(
`SELECT
cg.id,
cg.group_name,
cg.description,
cg.created_at,
COUNT(c.id) as contact_count
FROM contact_groups cg
LEFT JOIN contacts c ON cg.id = c.group_id AND c.tenant_id = cg.tenant_id
WHERE cg.tenant_id = ?
GROUP BY cg.id, cg.group_name, cg.description, cg.created_at
ORDER BY cg.group_name ASC`,
[tenantId]
);
logger.info('Contact groups retrieved', { tenantId, count: groups.length });
return res.json({
success: true,
data: groups
});
} catch (error) {
logger.error('Error getting groups', {
tenantId,
error: error.message,
stack: error.stack
});
return res.status(500).json({
success: false,
error: 'Failed to load groups'
});
}
});
/**
* Create contact group
* POST /api/tenant/contact-groups
*/
static createGroup = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { group_name, description } = req.body;
logger.info('Creating contact group', { tenantId, group_name, description });
if (!group_name) {
return res.status(400).json({
success: false,
error: 'Group name is required'
});
}
try {
logger.info('Inserting group', { tenantId, group_name, description });
const [result] = await pool.query(
`INSERT INTO contact_groups (tenant_id, group_name, description)
VALUES (?, ?, ?)`,
[tenantId, group_name, description || null]
);
logger.info('Contact group created', { tenantId, groupId: result.insertId });
return res.json({
success: true,
message: 'Group created successfully',
data: { id: result.insertId }
});
} catch (error) {
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
success: false,
error: 'Group name already exists'
});
}
logger.error('Error creating group', {
tenantId,
error: error.message,
stack: error.stack,
code: error.code
});
return res.status(500).json({
success: false,
error: 'Failed to create group'
});
}
});
/**
* Update contact group
* PUT /api/tenant/contact-groups/:id
*/
static updateGroup = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { id } = req.params;
const { group_name, description } = req.body;
try {
const [result] = await pool.query(
`UPDATE contact_groups
SET group_name = ?, description = ?
WHERE id = ? AND tenant_id = ?`,
[group_name, description || null, id, tenantId]
);
if (result.affectedRows === 0) {
return res.status(404).json({
success: false,
error: 'Group not found'
});
}
logger.info('Contact group updated', { tenantId, groupId: id });
return res.json({
success: true,
message: 'Group updated successfully'
});
} catch (error) {
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
success: false,
error: 'Group name already exists'
});
}
logger.error('Error updating group', { tenantId, groupId: id, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to update group'
});
}
});
/**
* Delete contact group
* DELETE /api/tenant/contact-groups/:id
*/
static deleteGroup = asyncHandler(async (req, res) => {
const tenantId = req.user.tenantId;
const { id } = req.params;
try {
// Check if it's the default group
const [group] = await pool.query(
'SELECT group_name FROM contact_groups WHERE id = ? AND tenant_id = ?',
[id, tenantId]
);
if (group.length === 0) {
return res.status(404).json({
success: false,
error: 'Group not found'
});
}
if (group[0].group_name === 'Default') {
return res.status(400).json({
success: false,
error: 'Cannot delete default group'
});
}
const [result] = await pool.query(
'DELETE FROM contact_groups WHERE id = ? AND tenant_id = ?',
[id, tenantId]
);
logger.info('Contact group deleted', { tenantId, groupId: id });
return res.json({
success: true,
message: 'Group deleted successfully'
});
} catch (error) {
logger.error('Error deleting group', { tenantId, groupId: id, error: error.message });
return res.status(500).json({
success: false,
error: 'Failed to delete group'
});
}
});
}
module.exports = ContactController;
|